package com.nondo.dean.saprfc.service;

import com.nondo.dean.common.tool.StringUtils;
import com.nondo.dean.common.web.View;
import com.nondo.dean.saprfc.common.DBUtil;
import com.nondo.dean.saprfc.common.SapUtil;
import com.nondo.dean.saprfc.common.U8AccountBean;
import com.nondo.dean.saprfc.common.Util;
import com.nondo.dean.saprfc.domain.TransferDetailBean;
import com.nondo.dean.saprfc.domain.TransferMainBean;
import com.sap.conn.jco.JCoException;
import com.sap.conn.jco.JCoFunction;
import com.sap.conn.jco.JCoTable;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @author xiaofan
 * @Description: 经销商打款记录传输处理
 * @throws
 * @date 2018-06-2015:28
 * @Version
 */
@Component
public class CrmTransferDetailService {

    @Autowired
    RestTemplate restTemplate;

    private Map<String,String> tmp_map = null;

    /**
     * sap消息校验
     */
    private static final String MESSAGE_SUCCESS_MARK="RIGHT";
    private static final String MESSAGE_ERROR_MARK="MSG_ERR";
    private static final String SAP_CODE="SAP_CODE";
    private static final String U8_CODE="U8_CODE";

    /**
     * 打款记录传输到sap
     * @param bean
     * @param sapClient
     * @return
     */
    public Map<String,String> synTransferDetailToSap(TransferMainBean bean,String sapClient){
        Map<String,String> resMap = new HashMap<>();
        //传SAP
        String header = bean.getRemitTanceTime()+" "+bean.getBankName();
        JCoFunction function = SapUtil.getFunction(sapClient,"Z_ND_OA_ACC_DOC_POST");
        function.getImportParameterList().setValue("IM_HEADER_TXT",header);
        function.getImportParameterList().setValue("IM_DATUM",bean.getRemitTanceTime());
        function.getImportParameterList().setValue("IM_UNAME",bean.getSapAccount());
        JCoTable IT_ACCOUNTGL = function.getTableParameterList().getTable("IT_ACCOUNTGL");
        JCoTable IT_CURRAMOUNT = function.getTableParameterList().getTable("IT_CURRAMOUNT");
        JCoTable IT_EXTENSION2 = function.getTableParameterList().getTable("IT_EXTENSION2");
        //主表头传输
        transferDetailMain(bean,IT_ACCOUNTGL,IT_CURRAMOUNT,IT_EXTENSION2,header);
        //打款明细传输
        transferDetail(bean,IT_ACCOUNTGL,IT_CURRAMOUNT,IT_EXTENSION2);
        //执行方法
        resMap = execute(bean,function,sapClient);

        return  resMap;
    }

    /**
     * 执行传输sap方法
     * @param function
     * @param sapClient
     * @return
     */
    public Map<String,String> execute(TransferMainBean bean,JCoFunction function,String sapClient){
        Map<String,String> resMap = new HashMap<>();
        try {
            function.execute(SapUtil.getDestination(sapClient));
            //SAP凭证号
            String voucherNumber = function.getExportParameterList().getString("EX_BELNR");
            JCoTable v_return = function.getTableParameterList().getTable("IT_RETURN");
            if(StringUtils.isNotBlank(voucherNumber)){
                //更新总代系统
                tmp_map = this.updateCrmFinanceToU8(bean,voucherNumber);
                resMap.put(CrmTransferDetailService.SAP_CODE,voucherNumber);
                resMap.put(CrmTransferDetailService.MESSAGE_SUCCESS_MARK,"在Sap中创建成功,凭证号为：" + voucherNumber);
                resMap.putAll(tmp_map);
            }else{
                resMap.put(CrmTransferDetailService.MESSAGE_ERROR_MARK,SapUtil.writeSapMessage(v_return));
            }

        } catch (JCoException e) {
            e.printStackTrace();
        }

        return resMap;
    }

    /**
     * 头传输
     * @param bean
     * @param IT_ACCOUNTGL
     * @param IT_CURRAMOUNT
     * @param IT_EXTENSION2
     * @param header
     */
    public void transferDetailMain(TransferMainBean bean,JCoTable IT_ACCOUNTGL,JCoTable IT_CURRAMOUNT,JCoTable IT_EXTENSION2,String header){
        String subject = Util.lpad(bean.getSapBankSubject(),10);
        IT_ACCOUNTGL.appendRow();
        IT_ACCOUNTGL.setValue("ITEMNO_ACC", 1);
        IT_ACCOUNTGL.setValue("COMP_CODE", "ND00");
        IT_ACCOUNTGL.setValue("GL_ACCOUNT",Util.lpad(subject,10));
        IT_ACCOUNTGL.setValue("ITEM_TEXT", header);

        IT_CURRAMOUNT.appendRow();
        IT_CURRAMOUNT.setValue("ITEMNO_ACC", 1);
        IT_CURRAMOUNT.setValue("CURRENCY", "CNY");
        IT_CURRAMOUNT.setValue("AMT_DOCCUR", bean.getTotalAmount());

        IT_EXTENSION2.appendRow();
        IT_EXTENSION2.setValue("STRUCTURE", "ZOA_ACC_EXTENSION");
        IT_EXTENSION2.setValue("VALUEPART1", "000000000140 206");
    }

    /**
     * 判断资金用途
     * @param moneyUsed
     * @return
     */
    public String judgeMoneyUsed(Integer moneyUsed){
        String returnMoneyUsed="";
        if(1== moneyUsed){
            returnMoneyUsed="销售回款";
        }else if(2 == moneyUsed){
            returnMoneyUsed="饰品物资回款";
        }else if(3 == moneyUsed){
            returnMoneyUsed="保证金";
        }else if(4 == moneyUsed){
            returnMoneyUsed="设计定金";
        }
        return returnMoneyUsed;
    }

    /**
     * 打款明细
     * @param bean
     * @param IT_ACCOUNTGL
     * @param IT_CURRAMOUNT
     * @param IT_EXTENSION2
     */
    public void transferDetail(TransferMainBean bean,JCoTable IT_ACCOUNTGL,JCoTable IT_CURRAMOUNT,JCoTable IT_EXTENSION2) {
        int index = 1;
        for (TransferDetailBean detailBean : bean.getTransferDetailBeanList()) {
            index++;
            String v_tmp_crmCode = detailBean.getCrmCode();
            if (!"".equals(detailBean.getProxyCode()) && 1 == detailBean.getMoneyUsed()) {
                v_tmp_crmCode = detailBean.getProxyCode();//总代
            }
            String itemText = detailBean.getRemitTanceTime() + " " + bean.getBankName() + " " + judgeMoneyUsed(detailBean.getMoneyUsed()) + " " + detailBean.getRegionName() + " " + detailBean.getCrmCode();
            String valuepart = Util.lpad(index + "", 10) + "19";
            String tmpSubject = "";
            if (1 == detailBean.getMoneyUsed() || 2 == detailBean.getMoneyUsed()) {
                tmpSubject = "0220301000";
                valuepart = valuepart + "A";
            } else if (3 == detailBean.getMoneyUsed() || 4 == detailBean.getMoneyUsed()) {
                tmpSubject = "0224101000";
                valuepart = valuepart + "D";
            }
            IT_ACCOUNTGL.appendRow();
            IT_ACCOUNTGL.setValue("ITEMNO_ACC", index);
            IT_ACCOUNTGL.setValue("COMP_CODE", "ND00");
            IT_ACCOUNTGL.setValue("GL_ACCOUNT", tmpSubject);
            IT_ACCOUNTGL.setValue("CUSTOMER", v_tmp_crmCode);//总代或经销商
            IT_ACCOUNTGL.setValue("ITEM_TEXT", itemText);

            IT_CURRAMOUNT.appendRow();
            IT_CURRAMOUNT.setValue("ITEMNO_ACC", index);
            IT_CURRAMOUNT.setValue("CURRENCY", "CNY");
            IT_CURRAMOUNT.setValue("AMT_DOCCUR", Util.getDoubleValue(detailBean.getDealAmount()) * -1);

            IT_EXTENSION2.appendRow();
            IT_EXTENSION2.setValue("STRUCTURE", "ZOA_ACC_EXTENSION");
            IT_EXTENSION2.setValue("VALUEPART1", valuepart);
        }
    }

    /**
     * 更新总代系统
     * @param bean
     * @param voucherNumber
     * @return
     */
    public Map<String,String> updateCrmFinanceToU8(TransferMainBean bean,String voucherNumber){
        String v_sql;
        String tmp_err="";
        Map<String,String> newMap= new HashMap<>();
        for (TransferDetailBean detailBean : bean.getTransferDetailBeanList()) {
            String toU8="";
            if(!"".equals(detailBean.getProxyCode()) && !detailBean.getCrmCode().equals(detailBean.getProxyCode()) && 1 == detailBean.getMoneyUsed()){
                toU8="1";
            }else{//不需要写入总代系统
                continue;
            }
            String vouchId = Util.lpad(detailBean.getId().toString(),10);
            String v_tmp_iyear = detailBean.getRemitTanceTime().substring(0,4);
            String v_tmp_iPeriod=Util.getDate(detailBean.getRemitTanceTime(), "9");
            U8AccountBean accountBean= U8AccountBean.getAccountBean(detailBean.getProxyCode(), v_tmp_iyear);
            String U8_DBNAME=accountBean.getDbname();
            String U8_CACCID=accountBean.getCaccid();

            v_sql="select count(1) as cnt from "+U8_DBNAME+"..Ap_CloseBill where cVouchID='"+vouchId+"'";
            tmp_map=DBUtil.executeQueryMap(DBUtil.OA, v_sql);
            String cnt=Util.null2String(tmp_map.get("cnt"));
            if(!"0".equals(cnt)){
                tmp_err+="<br/>数据已存在-->客户:"+detailBean.getCrmName()+" 时间: "+detailBean.getRemitTanceTime()+" 金额:"+detailBean.getDealAmount()+"元;总代帐套:"+U8_CACCID+" 会计年度:"+v_tmp_iyear+";";
                continue;
            }

            v_sql="select cCusDepart,cCusPPerson from "+U8_DBNAME+"..customer where ccuscode='"+detailBean.getCrmCode()+"'";
            tmp_map= DBUtil.executeQueryMap(DBUtil.OA, v_sql);

            String v_tmp_cDeptCode=Util.null2String(tmp_map.get("ccusdepart"));
            String v_tmp_cPerson=Util.null2String(tmp_map.get("ccuspperson"));
            String v_tmp_cSSCode= 4 == detailBean.getTransactionMode() ? "1":"2";
            v_sql="select ccode from "+U8_DBNAME+"..Ap_SStyleCode where cflag='AR' and csettlestyle='"+v_tmp_cSSCode+"'";
            tmp_map=DBUtil.executeQueryMap(DBUtil.OA, v_sql);

            String subject="224101";//将所有款项转入浪度家私科目中
            v_sql="select top 1 vt_id from "+U8_DBNAME+"..VoucherTemplates where vt_cardnumber='AR_R' and vt_templatemode=0";
            tmp_map=DBUtil.executeQueryMap(DBUtil.OA, v_sql);

            String v_tmp_VT_ID=Util.null2String(tmp_map.get("vt_id"));
            v_sql="update ufsystem..ua_identity set ifatherid=ifatherid+1,ichildid=ichildid+1 where cacc_id='"+U8_CACCID+"' and cvouchtype='SK'";
            DBUtil.executeUpdate(DBUtil.OA,v_sql);

            v_sql="select * from ufsystem..ua_identity where cacc_id='"+U8_CACCID+"' and cvouchtype='SK'";
            tmp_map=DBUtil.executeQueryMap(DBUtil.OA, v_sql);

            String iFatherId=Util.null2String(tmp_map.get("ifatherid"));
            String iChildId=Util.null2String(tmp_map.get("ichildid"));

            String deptCode = "".equals(v_tmp_cDeptCode) ? "NULL" : "'" + v_tmp_cDeptCode + "'";
            String itemText=detailBean.getRemitTanceTime()+" "+bean.getBankName()+" "+judgeMoneyUsed(detailBean.getMoneyUsed())+" "+detailBean.getRegionName()+" "+detailBean.getCrmName();

            v_sql="insert into "+U8_DBNAME+"..Ap_CloseBill(cVouchType,cVouchID,dVouchDate,iPeriod,cDwCode,cDeptCode,cPerson,cSSCode,cexch_name,iExchRate,iAmount,iAmount_f,iRAmount,iRAmount_f,cOperator,bPrePay,bStartFlag,cCode,iPayForOther,cFlag,bSend,bReceived,iID,bFromBank,bToBank,bSure,VT_ID,cCheckMan,cDigest,cNoteNo)"
                    +"values('48','"+vouchId+"','"+detailBean.getRemitTanceTime()+"','"+v_tmp_iPeriod+"','"+detailBean.getCrmCode()+"',"+deptCode+",'"+v_tmp_cPerson+"','"+v_tmp_cSSCode+"','人民币','1',"+detailBean.getDealAmount()+","+detailBean.getDealAmount()+","+detailBean.getDealAmount()+","+detailBean.getDealAmount()+",'"+bean.getUserName()+"','0','0','"+subject+"','0','AR','0','0','"+iFatherId+"','0','0','0','"+v_tmp_VT_ID+"','"+bean.getUserName()+"','"+itemText+"','"+voucherNumber+"')";
            int count1 = DBUtil.executeUpdate(DBUtil.OA,v_sql);
            v_sql="insert into "+U8_DBNAME+"..Ap_CloseBills(iID,ID,iType,bPrePay,cCusVen,iAmt_f,iAmt,iRAmt_f,iRAmt,cKm,cDepCode,cPersonCode)"
                    +"values('"+iFatherId+"','"+iChildId+"','0','0','"+detailBean.getCrmCode()+"',"+detailBean.getDealAmount()+","+detailBean.getDealAmount()+","+detailBean.getDealAmount()+","+detailBean.getDealAmount()+",'1122',"+deptCode+",'"+v_tmp_cPerson+"')";
            int count2 = DBUtil.executeUpdate(DBUtil.OA,v_sql);
            v_sql="INSERT INTO "+U8_DBNAME+"..Ap_Detail ( iPeriod, iSignSeq, cVouchType, cVouchID, dVouchDate, dRegDate, dPZDate, cDwCode, cDeptCode, cPerson, cCode, citem_Class, cItemCode, cItemName, cDigest, cExch_name, iExchRate, iDAmount, iCAmount, iDAmount_f, iCAmount_f, cOrderNo, cSSCode, cProcStyle, cCancelNo, iFlag, cCoVouchType, cCoVouchID, cFlag, cDefine1, cDefine2, cDefine3, cDefine4, cDefine5, cDefine6, cDefine7, cDefine8, cDefine9, cDefine10, cDefine11, cDefine12, cDefine13, cDefine14, cDefine15, cDefine16, cContractType, cContractID ) " +
                    "SELECT iPeriod, NULL, cVouchType, cVouchID, dVouchDate, dVouchDate, dVouchDate, cDwCode, cDeptCode, cPerson, cCode, citem_Class, cItemCode, cItemName, cDigest, cExch_name, iExchRate, CASE WHEN cVouchType = '48' THEN iAmount ELSE - iAmount END, 0, CASE WHEN cVouchType = '48' THEN iAmount_f ELSE - iAmount_f END, 0, cOrderNo, cSSCode, cVouchType, cFlag + cVouchType + cVouchID, 6, cVouchType, cVouchID, cFlag, cDefine1, cDefine2, cDefine3, cDefine4, cDefine5, cDefine6, cDefine7, cDefine8, cDefine9, cDefine10, cDefine11, cDefine12, cDefine13, cDefine14, cDefine15, cDefine16, cContractType, cContractID FROM "+U8_DBNAME+"..Ap_CloseBill Where iID='"+iFatherId+"'";
            int count3 = DBUtil.executeUpdate(DBUtil.OA,v_sql);
            v_sql="INSERT INTO "+U8_DBNAME+"..Ap_Detail ( iPeriod, iSignSeq, cVouchType, cVouchID, dVouchDate, dRegDate, dPZDate, cDwCode, cDeptCode, cPerson, iClosesID, cCode, citem_Class, cItemCode, cItemName, cDigest, cExch_name, iExchRate, iDAmount, iCAmount, iDAmount_f, iCAmount_f, cOrderNo, cSSCode, cProcStyle, cCancelNo, bPrePay, iFlag, cCoVouchType, cCoVouchID, iCoClosesID, cFlag, cDefine1, cDefine2, cDefine3, cDefine4, cDefine5, cDefine6, cDefine7, cDefine8, cDefine9, cDefine10, cDefine11, cDefine12, cDefine13, cDefine14, cDefine15, cDefine16, cContractType, cContractID ) " +
                    "SELECT iPeriod, NULL, cVouchType, cVouchID, dVouchDate, dVouchDate, dVouchDate, cCusVen, cDepCode, cPersonCode, ID, cKm, cXmClass, cXm, t2.cItemName, cDigest, cExch_name, iExchRate, 0, CASE WHEN cVouchType = '48' THEN iAmt ELSE - iAmt END, 0, CASE WHEN cVouchType = '48' THEN iAmt_f ELSE - iAmt_f END, cOrderID, cSSCode, cVouchType, cFlag + cVouchType + cVouchID, CASE WHEN iType = 1 THEN 1 ELSE 0 END, CASE WHEN iType < 2 THEN 0 ELSE 10 END, cVouchType, cVouchID, ID, cFlag, cDefine1, cDefine2, cDefine3, cDefine4, cDefine5, cDefine6, cDefine7, cDefine8, cDefine9, cDefine10, cDefine11, cDefine12, cDefine13, cDefine14, cDefine15, cDefine16, cConType, cConID FROM "+U8_DBNAME+"..Ap_CloseBill t1 INNER JOIN "+U8_DBNAME+"..Ap_CloseBills t2 ON t1.iID = t2.iID WHERE t1.iID ='"+iFatherId+"'";
            int count4 = DBUtil.executeUpdate(DBUtil.OA,v_sql);
            if(count1 < 0 || count2 < 0 || count3 < 0 || count4 < 0){
                //失败
                v_sql="delete from "+U8_DBNAME+"..Ap_Detail where cVouchID='"+vouchId+"'";
                DBUtil.executeUpdate(DBUtil.OA,v_sql);
                v_sql="delete from "+U8_DBNAME+"..Ap_CloseBills where iID='"+iFatherId+"'";
                DBUtil.executeUpdate(DBUtil.OA,v_sql);
                v_sql="delete from "+U8_DBNAME+"..Ap_CloseBill where iID='"+iFatherId+"'";
                DBUtil.executeUpdate(DBUtil.OA,v_sql);
                tmp_err+="<br/>行项目异常-->客户:"+detailBean.getCrmName()+" 时间: "+detailBean.getRemitTanceTime()+" 金额:"+detailBean.getDealAmount()+"元;";
            }else {
                //成功
                Map<String,Object> result= new HashMap<>();
                result.put(CrmTransferDetailService.U8_CODE,vouchId);
                result.put("id",detailBean.getId());
                this.updateProxyCode(result);
            }
        }
        newMap.put(CrmTransferDetailService.MESSAGE_ERROR_MARK,tmp_err);
        return newMap;
    }

    /**
     * 修改总代编号
     * @param newMap
     */
    public void updateProxyCode(Map<String,Object> newMap){

        restTemplate.postForEntity("http://dean-order/order/v1inner/transferDetail/update/proxy", newMap,View.class
                ).getBody();

    }
}
